package com.heima.comment.service.impl;
import java.math.BigDecimal;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    GreenScan greenScan;
    @Autowired
    UserFeign userFeign;
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 保存评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {

        //参数校验  校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //阿里云校验评论内容是否违规
        String content= dto.getContent();
        try {

            ScanResult scanResult = greenScan.greenTextScan(dto.getContent());
            //获取过滤后的字符  文本内容违规  有问题不报异常，替换为**
            if (scanResult.getFilteredContent()!=null){
                content = scanResult.getFilteredContent();
            }


        } catch (Exception e) {
            e.printStackTrace();
            log.info("阿里云校验内容失败  失败原因 {}" ,e.getMessage());
        }

        //远程User微服务 查询当前登陆用户信息
        ResponseResult<ApUser> loginUser = userFeign.findUserById(user.getId());
        ApUser apUser = loginUser.getData();

        //创建评论信息，并保存到mongo
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setArticleId(dto.getArticleId());
        apComment.setType((short)0);
        //apComment.setChannelId(0);
        apComment.setContent(content);
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short)0);
       // apComment.setLongitude(new BigDecimal("0"));
       // apComment.setLatitude(new BigDecimal("0"));
        //apComment.setAddress("");
        //apComment.setOrd(0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());



        mongoTemplate.save(apComment);

        return ResponseResult.okResult();
    }

    @Autowired
    RedissonClient redissonClient;

    /**
     * 点赞评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {

        //参数校验  评论id不能为空  operation必须为 0  或  1
        if (dto.getCommentId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"评论id不能为空");
        }
        if (dto.getOperation()!=0 && dto.getOperation()!=1){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //分布式锁
        RLock likeLock = redissonClient.getLock("likeLock");
        //阻塞加锁
        likeLock.lock();


        ApComment apComment;

        try {
            //根据评论id查询评论数据， 为null返回错误信息
            apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
            if (apComment==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            //获取当前登录用户
            ApUser user = AppThreadLocalUtils.getUser();

            //是否已经评论
            ApCommentLike apCommentLike = mongoTemplate.findOne(Query.query(Criteria.
                    where("authorId").is(user.getId()).
                    and("commentId").is(dto.getCommentId())),
                    ApCommentLike.class);
            //如果是点赞操作 判断是否已经点赞
            if (apCommentLike!=null && dto.getOperation()==0){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, " 请勿重复点赞");
            }

            if (dto.getOperation()==0){
                //未点过赞   保存点赞信息到mongo
                apCommentLike =new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(dto.getCommentId());
                apCommentLike.setOperation((short)0);

                mongoTemplate.save(apCommentLike);

                //并修改评论信息的点赞数量( + 1)
                apComment.setLikes(apComment.getLikes()+1);
                mongoTemplate.save(apComment);
            }

            //如果是取消点赞操作

            if (dto.getOperation()==1){
                //删除点赞信息
                mongoTemplate.remove(Query.query(Criteria.
                                where("authorId").is(user.getId()).
                                and("commentId").is(dto.getCommentId())),
                        ApCommentLike.class);

                //并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
                apComment.setLikes(apComment.getLikes()<=0?0:apComment.getLikes()-1);
                mongoTemplate.save(apComment);
            }
        } finally {

            //解锁
            likeLock.unlock();
        }

        //返回结果时，需要返回点赞数量  返回的key要求必须是:  likes

        Map<String,Object> map =new HashMap<>();
        map.put("likes",apComment.getLikes());
        return ResponseResult.okResult(map);
    }


    /**
     * 根据文章id查询评论列表
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        //参数校验  校验文章id
        if (dto.getArticleId()==null||dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Integer size = dto.getSize();
        if (size==null ||size<=0){
            size=10;
        }

        if(dto.getMinDate() == null){
            dto.setMinDate(new Date());
        }
// 判断是否
        //2 查询Mongo文章所有评论列表
        List<ApComment> apCommentList;
        // 文章评论的首页
        if (dto.getIndex().intValue() == 1) {
            //查询热点评论  （最多5条） (条件: flag=1, 文章id, 点赞降序)
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is(1))
                    .with(Sort.by(Sort.Direction.DESC, "likes"));
            apCommentList = mongoTemplate.find(query, ApComment.class);
            // 热点集合不为空
            if (CollectionUtils.isNotEmpty(apCommentList)) {
                size = size - apCommentList.size();
                List<ApComment> normalComments = mongoTemplate.find(getQuery(dto, size), ApComment.class);
                apCommentList.addAll(normalComments);
            } else {
                apCommentList = mongoTemplate.find(
                        getQuery(dto, size),
                        ApComment.class
                );
            }
        } else {
            apCommentList = mongoTemplate.find(
                    getQuery(dto, size),
                    ApComment.class
            );
        }
        //3 封装查询结果
        //3.1 用户未登录 直接返回评论列表
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentList);
        }
        //3.2 用户登录，需要加载当前用户对评论点赞的列表
        // 获取文章对应的所有评论ID列表
        List<String> idList = apCommentList.stream()
                .map(ApComment::getId)
                .collect(Collectors.toList());
        // 查询 点赞批量列表 按照评论id 筛选
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(
                Query.query(Criteria.where("commentId").in(idList)
                        .and("authorId").is(user.getId()))
                , ApCommentLike.class);
        // 遍历当前用户点赞列表 和当前评论列表
        if (CollectionUtils.isNotEmpty(apCommentList)
                && CollectionUtils.isNotEmpty(apCommentLikes)) {
            // 获取点过赞的评论id
            List<String> commentIds = apCommentLikes.stream()
                    .map(ApCommentLike::getCommentId).collect(Collectors.toList());
            // 遍历评论列表，将comment 转为 commentVO
            return ResponseResult.okResult(apCommentList.stream()
                    .map(comment -> parseCommentVO(comment, commentIds)));
        }
        return ResponseResult.okResult(apCommentList);
    }

    /**
     * 将comment 转为 vo对象   根据likes情况判断是否点过赞
     *
     * @param apComment
     * @param commentIds
     * @return
     */
    private ApCommentVo parseCommentVO(ApComment apComment, List<String> commentIds) {
        ApCommentVo apCommentVo = new ApCommentVo();
        BeanUtils.copyProperties(apComment, apCommentVo);
        //遍历当前用户点赞列表
        if (commentIds.contains(apCommentVo.getId())) {
            apCommentVo.setOperation((short) 0);
        }
        return apCommentVo;
    }

    /**
     * 构建查询条件
     */
    private Query getQuery(CommentDTO dto, Integer size) {
        return Query.query(Criteria.where("articleId").is(dto.getArticleId())
                .and("flag").is(0).and("createdTime").lt(dto.getMinDate()))
                .limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime"));
    }
}
